package com.turtle.contentcenter.contents.controller;

import com.turtle.contentcenter.contents.dto.UserDTO;
import com.turtle.contentcenter.contents.entity.Share;
import com.turtle.contentcenter.contents.service.IShareService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 分享模块
 *
 * @author turtle
 * @date： 2020-04-17
 */
@RestController
@Api(value = "分享", tags = "分享模块")
@RequestMapping("/contents/share")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))

public class ShareController {

    private final IShareService shareService;
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;

    /**
     * 通过id获取文章分享信息
     *
     * @param id
     * @return Share
     */
    @GetMapping("/{id}")
    @ApiOperation("通过id获取文章分享信息")

    public Share getShareById(@Validated @PathVariable Integer id) {
        Share share = shareService.getById(id);

        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
        String targetUrl = instances.stream()
                .map(instance -> instance.getUri() + "/users/user/{id}")
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);
        UserDTO userDTO = restTemplate.getForObject(targetUrl, UserDTO.class, share.getId());
        share.setWxNickname(userDTO.getWxNickname());
        return share;
    }

}